package logic

import (
	"fmt"
	"os"
	"path"
	"strings"
	"time"

	"gddgame.cc/galaxy/utils"
)

type inlineLog struct {
	file   *os.File
	ticker *time.Ticker
}

func (log *inlineLog) Write(p []byte) (n int, err error) {
	return log.file.Write(p)
}

func (log *inlineLog) bindFile(fileName string) error {
	if err := log.getFile(fileName); err != nil {
		return err
	}
	go func() {
		now := time.Now()
		// 最小间隔1小时一个文件， 先只按时间，不安大小
		<-time.After(time.Minute*time.Duration(60-now.Minute()) + time.Second*time.Duration(61-now.Second()))
		_ = log.getFile(fileName)
		ticker := time.NewTicker(time.Minute * 24)
		log.ticker = ticker
		for _ = range ticker.C {
			// 重新调整文件
			_ = log.getFile(fileName)
		}
	}()
	return nil
}

func (log *inlineLog) getFile(fileName string) error {
	now := time.Now()
	fileName = strings.Replace(fileName, "%Y", utils.ToString(now.Year()), 1)
	fileName = strings.Replace(fileName, "%M", fmt.Sprintf("%02d", now.Month()), 1)
	fileName = strings.Replace(fileName, "%D", fmt.Sprintf("%02d", now.Day()), 1)
	fileName = strings.Replace(fileName, "%H", fmt.Sprintf("%02d", now.Hour()), 1)
	dir := path.Dir(fileName)
	if err := utils.Mkdir(dir); err != nil {
		return err
	}
	if file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644); err != nil {
		return err
	} else {
		// 关闭原有文件
		if log.file != nil {
			_ = log.file.Close()
		}
		log.file = file
	}
	return nil
}

func (log *inlineLog) Close() error {
	err := log.file.Close()
	log.file = nil
	return err
}
